package com.itheima.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.pojo.*;
import com.itheima.service.DeptService;
import com.itheima.service.EmpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 员工管理
 */
@Slf4j
@RequestMapping("/emps")
@RestController
public class EmpController {

    @Autowired
    private EmpService empService;
    @Autowired
    private DeptService deptService;

    @GetMapping
    private Result findPage ( EmpQueryParam empQueryParam ) {

        Page<Emp> page =new Page<>(empQueryParam.getPage(),empQueryParam.getPageSize());
        LambdaQueryWrapper<Emp> wrapper =new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(empQueryParam.getName()),Emp::getName,empQueryParam.getName());
        wrapper.eq(empQueryParam.getGender()!=null,Emp::getGender,empQueryParam.getGender());
        wrapper.between(empQueryParam.getBegin()!=null&&empQueryParam.getEnd()!=null,Emp::getEntryDate, empQueryParam.getBegin(), empQueryParam.getEnd());

        page = empService.page(page,wrapper);
        List<Emp> emps = page.getRecords();
        emps.forEach(emp -> {
            Dept dept = deptService.getById(emp.getDeptId());
            if(dept != null){
                emp.setDeptName(dept.getName());
            }
        });


        return Result.success(emps);
    }

    @PostMapping
    private Result save (@RequestBody  Emp emp ) throws Exception {
        empService.savaEmpAndExprList(emp);
        return Result.success();
    }

    @DeleteMapping
    public Result delete ( @RequestParam List<Integer> ids ) {
        empService.deleteEmpAndExprList(ids);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result getById ( @PathVariable("id") Integer id ) {
        Emp emp = empService.getEmpAndExprById(id);
        return Result.success(emp);
    }

    @PutMapping
    public Result update ( @RequestBody Emp emp ) {
        empService.updateEmpAndExprList(emp);
        return Result.success();
    }

    @GetMapping("/list")
    public Result findAllEmp () {
        List<Emp> empList = empService.list();
        return Result.success(empList);
    }
}